<script setup lang="ts">
import { ref, onUnmounted, onMounted, reactive } from 'vue'
import { setCache, COUNT_DOWN_KEY, X_TOKEN, X_EMAIL } from '@/util/cache'
import { getCookie, removeCookie, setCookie } from '@/util/cookie'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { requestToken, verifyToken } from '@/request/api'

interface SystemMessageForm {
  email: '',
  token: ''
}


const form = ref<SystemMessageForm>({
  email: '',
  token: ''
})
const tokenIsDisabled = ref(false)
const emailIsDisabled = ref(false)
const countdown = ref(0)

const ruleFormRef = ref<FormInstance>()


let timer: number | null = null


// 邮箱校验
const validate_email = (rule: any, value: any, callback: any) => {
  var emailRegExp = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
  var emailRegExp1 = /^([a-zA-Z]|[0-9])(\w|-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
  if ((!emailRegExp.test(value) && value != '') || (!emailRegExp1.test(value) && value != '')) {
    callback(new Error('请输入有效邮箱格式！'))
  } else {
    callback()
  }
}

const formEmailRule = [
  { required: true, message: '邮箱不能为空', trigger: 'blur' },
  { validator: validate_email, trigger: 'blur' }
]

const formTokenRule = [
  { required: true, message: '令牌不能为空', trigger: 'blur' }
]

const rules = reactive<FormRules<SystemMessageForm>>({})


const sendToken = async (formEl: FormInstance | undefined) => {
  rules.email = formEmailRule
  rules.token = []
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      requestToken({
        email: form.value.email
      }).then(res => {
        if (res.code === 200) {
          // 按钮置灰，邮箱输入框锁定
          countdownFunc(60)
          emailIsDisabled.value = true
          // 告知发送成功
          ElMessage({
            message: 'token发送成功，请注意邮箱查收！',
            type: 'success',
            plain: true
          })
        } else {
          ElMessage({
            message: 'token发送失败！',
            type: 'error',
            plain: true
          })
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

const countdownFunc = (seconds: number) => {
  console.log('sendToken')
  tokenIsDisabled.value = true
  countdown.value = seconds
  timer = setInterval(() => {
    countdown.value -= 1
    setCookie(COUNT_DOWN_KEY, countdown.value.toString(), { expires: new Date(new Date().getTime() + countdown.value * 1000) })
    if (countdown.value === 0) {
      clearInterval(timer as number)
      tokenIsDisabled.value = false
      removeCookie(COUNT_DOWN_KEY)
    }
  }, 1000)
}

onMounted(() => {
  const savedCountdown = getCookie(COUNT_DOWN_KEY)
  if (savedCountdown) {
    const remainingTime = parseInt(savedCountdown, 10)
    if (remainingTime > 0) {
      countdownFunc(remainingTime)
    }
  }
})


const submitForm = async (formEl: FormInstance | undefined) => {
  rules.email = formEmailRule
  rules.token = formTokenRule
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      verifyToken(form.value).then(res => {
        if (res.code === 200) {
          const { token, email } = form.value
          // 把邮箱和token都存入cache
          setCache(X_TOKEN, token)
          setCache(X_EMAIL, email)
          // 关闭弹框
          visible.value = false
          // 告知发送成功
          ElMessage({
            message: '验证成功！',
            type: 'success',
            plain: true
          })
        } else {
          ElMessage({
            message: '验证失败',
            type: 'error',
            plain: true
          })
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

onUnmounted(() => {
  if (timer !== null) {
    clearInterval(timer)
  }
})

const visible = ref<boolean>(true)
</script>

<template>
  <el-dialog v-model="visible" title="系统提示📢" width="500px" :close-on-click-modal="false"
             :close-on-press-escape="false" :show-close="false">
    <el-form :model="form" :label-position="'right'" :rules="rules" ref="ruleFormRef">
      <el-form-item>
        <el-text type="danger">
          由于服务器性能原因与联网检索API的请求限制，用户需要提供邮箱，以此接收系统发放的令牌。
          每个邮箱仅限制申请一个token，每个token限制10次联网检索API的请求。
        </el-text>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" autocomplete="off" :disabled="emailIsDisabled" />
      </el-form-item>
      <el-form-item label="令牌" prop="token">
        <el-input v-model="form.token" autocomplete="off" />
        <el-button type="primary" @click="sendToken(ruleFormRef)" :disabled="tokenIsDisabled">
          {{ tokenIsDisabled ? `发送令牌（${countdown}s）` : '发送令牌' }}
        </el-button>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="less">
::v-deep(.el-form-item__content) {
  flex-wrap: nowrap;
  gap: 5px
}
</style>
